﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Interop;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace GadgetBase
{
    public class DragedWindow : Window
    {
        private WindowInteropHelper wih;

        public IntPtr Handle
        {
            get
            {
                return wih.Handle;
            }
        }

        public DragedWindow()
        {
            wih = new WindowInteropHelper(this);

            base.Height = 300;
            base.Width = 300;
            base.SnapsToDevicePixels = true;            
        }


        public event GadgetWindowEventHandler2 Drop;
        public event GadgetWindowEventHandler2 BeginDrag;

        private bool isDraging = false;
        public bool IsDraging
        {
            get
            {
                return this.isDraging;
            }
        }

        protected override void OnMouseLeftButtonDown(MouseButtonEventArgs e)
        {
            base.OnMouseLeftButtonDown(e);

            OnDrag();
        }

        protected void OnDrag()
        {
            this.isDraging = true;
            OnBeginDrag();
            
            NativeMethods.ReleaseCapture();
            NativeMethods.SendMessage(this.Handle, NativeMethods.WM_NCLBUTTONDOWN, NativeMethods.HTCAPTION, 0);            
            
            this.isDraging = false;
            OnDrop();
        }

        protected virtual void OnDrop()
        {
            if (Drop != null)
            {
                Drop(this);
            }
        }

        protected virtual void OnBeginDrag()
        {
            if (BeginDrag != null)
            {
                BeginDrag(this);
            }
        }
    }
}
